package com.zhugang.week13.hash;

import java.util.HashSet;
import java.util.Set;

/**
 * @program algorithms
 * @description: removeDuplicateNodes
 * @author: chanzhugang
 * @create: 2022/12/03 21:13
 */
public class RemoveDuplicateNodes {

    /**
     * 面试题02.01 移除重复节点
     * https://leetcode.cn/problems/remove-duplicate-node-lcci/
     *
     * @param head
     * @return
     */
    public ListNode removeDuplicateNodes(ListNode head) {
        /**
         * 链表题套路：开辟新链表 + tail指针
         * 哈希集合判断是否出现过 + 开辟新链表 + tail
         */
        ListNode newNode = new ListNode();
        ListNode tail = newNode;
        Set<Integer> set = new HashSet<>();
        ListNode p = head;
        while (p != null) {
            ListNode temp = p.next;
            if (!set.contains(p.val)) {
                set.add(p.val);
                tail.next = p;
                tail = p;
                tail.next = null;
            }
            p = temp;
        }
        return newNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        public ListNode() {

        }
    }
}